package cn.ynrcb.personnelfile.common.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateUtils;

import java.io.File;
import java.net.URL;
import java.util.Date;

/**
 * 附件上传阿里云OSS
 * @author swb
 * @version created at 2021年4月24日 下午4:48:40
 */
@Slf4j
public class OSSUtil {
    private volatile static OSSClient instance;
    public static final String basePath = "kmzmcxbeian/"; //中国（云南）自由贸易试验区昆明片区创新奖励备案登记系统

    private OSSUtil() {
    }

    /**
     * 单例
     * @return  OSS工具类实例
     */
    private static OSSClient getOSSClient() {
        if (instance == null) {
            synchronized (OSSUtil.class) {
                if (instance == null) {
                    instance = new OSSClient(OSS_END_POINT, new DefaultCredentialProvider(OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET),null);
                }
            }
        }
        return instance;
    }

    //OSS 的地址
    private final static String OSS_END_POINT = "https://govstatic.kunming.cn";
    //OSS 的key值
    private final static String OSS_ACCESS_KEY_ID = "LTAIUPyjuX5c99kL";
    //OSS 的secret值
    private final static String OSS_ACCESS_KEY_SECRET = "uWBO87ApMPNtrDyJCoKYDDH3WRyTNj";
    //OSS 的bucket名字
    private final static String OSS_BUCKET_NAME = "govstatic";

    /**
     * 上传文件---去除URL中的？后的时间戳
     * @param file 文件
     * @param key 上传到OSS上文件的路径
     * @return 文件的访问地址
     */
    public static String upload(File file, String key) {
        OSSUtil.createBucket();
        OSSUtil.uploadFile(file, key);
        String fileOssURL = OSSUtil.getImgUrl(key);
//        int firstChar = fileOssURL.indexOf("?");
//        if (firstChar > 0) {
//            fileOssURL = fileOssURL.substring(0, firstChar);
//        }
        return fileOssURL;
    }

    /**
     * 当Bucket不存在时创建Bucket
     *
     * @throws OSSException 异常
     * @throws ClientException Bucket命名规则：
     *                         1.只能包含小写字母、数字和短横线，
     *                         2.必须以小写字母和数字开头和结尾
     *                         3.长度在3-63之间
     */
    private static void createBucket() {
        try {
            if (!OSSUtil.getOSSClient().doesBucketExist(OSS_BUCKET_NAME)) {//判断是否存在该Bucket，不存在时再重新创建
                OSSUtil.getOSSClient().createBucket(OSS_BUCKET_NAME);
            }
        } catch (Exception e) {
            log.error("创建Bucket失败,请核对Bucket名称(规则：只能包含小写字母、数字和短横线，必须以小写字母和数字开头和结尾，长度在3-63之间)");
        }
    }


    /**
     * 上传到OSS服务器  如果同名文件会覆盖服务器上的
     * @param file 文件
     * @param key  上传到OSS上文件的路径
     */
    public static void uploadFile(File file, String key) {
        try{
            //上传文件
            PutObjectResult putResult = OSSUtil.getOSSClient().putObject(OSS_BUCKET_NAME, key, file);
            log.info(putResult.toString());
        } catch (Exception e) {
            log.error("上传文件失败");
        }
    }


    /**
     * 获得文件路径
     * @param key  文件在OSS上的路径
     * @return 文件的路径
     */
    public static String getImgUrl(String key) {
//        Date expiration = DateUtils.addDays(new Date(), 365 * 10);	//设置URL过期时间为10年
    	Date expiration = DateUtils.addHours(new Date(), 2); //设置URL过期时间为2小时
        URL url = OSSUtil.getOSSClient().generatePresignedUrl(OSS_BUCKET_NAME, key,  expiration);
        if (url == null) {
            log.error("获取oss文件URL失败");
        }
        return url.toString();
    }

    /**
     * 从oss下载文件到本地目录
     * @author swb
     * @version created at 2020年4月15日 下午5:14:06
     * @param key
     * @param descFilePath
     * @param fileName
     * @return
     */
	public static String downloadOSSFile(String key, String descFilePath, String fileName) {
		String downloadFilePath = "";
		try{
			File file = new File(descFilePath);
            if (!file.exists()){
                file.mkdirs();
            }

            descFilePath = descFilePath + key.substring(0, key.lastIndexOf("/") + 1);
            FileUtils.checkExist(new File(descFilePath));
            downloadFilePath = descFilePath + fileName;
            File downloadedFile = new File(downloadFilePath);
            if(!downloadedFile.exists()) {
            	OSSUtil.getOSSClient().getObject(new GetObjectRequest(OSS_BUCKET_NAME, key), new File(downloadFilePath));
            }
		} catch (Exception e) {
			e.printStackTrace();
			log.error("下载OSS文件失败！");
		}
		return downloadFilePath;
	}

    /**
     * 判断OSS服务文件上传时文件的contentType
     *
     * @param FilenameExtension 文件后缀
     * @return 后缀
     */
    private static String getContentType(String FilenameExtension) {
        if (FilenameExtension.equalsIgnoreCase("bmp")) {
            return "image/bmp";
        }
        if (FilenameExtension.equalsIgnoreCase("gif")) {
            return "image/gif";
        }
        if (FilenameExtension.equalsIgnoreCase("jpeg") ||
                FilenameExtension.equalsIgnoreCase("jpg") ||
                FilenameExtension.equalsIgnoreCase("png")) {
            return "image/jpeg";
        }
        if (FilenameExtension.equalsIgnoreCase("html")) {
            return "text/html";
        }
        if (FilenameExtension.equalsIgnoreCase("txt")) {
            return "text/plain";
        }
        if (FilenameExtension.equalsIgnoreCase("vsd")) {
            return "application/vnd.visio";
        }
        if (FilenameExtension.equalsIgnoreCase("pptx") ||
                FilenameExtension.equalsIgnoreCase("ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if (FilenameExtension.equalsIgnoreCase("docx") ||
                FilenameExtension.equalsIgnoreCase("doc")) {
            return "application/msword";
        }
        if (FilenameExtension.equalsIgnoreCase("xml")) {
            return "text/xml";
        }
        return "image/jpeg";
    }
}
